<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/2/19 0019
  Time: 11:09
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="/bootstrap-3.3.7-dist/css/bootstrap.css"/>
    <link rel="stylesheet" href="/css/kefu.css" type="text/css"/>
    <script type="text/javascript" src="/bootstrap-3.3.7-dist/js/jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
    <style>
        .content_display {
            display: none;
        }
    </style>
</head>
<body>
<div class="chat_box">
    <div class="chat_box_left">
        <div class="chat_box_left_header">
            <div class="header_left">
                <img src="${sessionScope.user.image}"/>
            </div>
            <div class="header_right" id="${sessionScope.user.id}">${sessionScope.user.username}</div>
        </div>
        <div class="chat_box_left_reminder">
            欧企查在线用户列表
        </div>
        <ul class="chat_box_left_bottom">
            <c:forEach items="${guests}" var="guest">
                <li id="${guest.id}">
                    <div class="li_left">
                        <img src="${guest.image}"/>
                    </div>
                    <div class="li_right">
                        <span class="account">${guest.username}</span>
                        <span class="account_accept_message">该用户接收的信息</span>
                    </div>
                </li>
            </c:forEach>
        </ul>
    </div>
    <div class="chat_box_right">
        <div class="chat_box_right_header">
            <%--正在与账户<span>用户一</span>的用户进行在线会话--%>
        </div>
        <div class="chat_box_right_center">
            <c:forEach items="${guests}" var="guest">
                <div class="${guest.id}">

                </div>
            </c:forEach>
        </div>
        <div class="chat_box_right_bottom">
            <textarea id="textarea"></textarea>
            <button class="sendBtn">发送</button>
        </div>
    </div>
</div>

<script>
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/websocket");
    } else {
        alert('当前浏览器 Not support websocket')
    }
    //连接发生错误的回调方法
    websocket.onerror = function () {
        alert("WebSocket连接发生错误");
        // setMessageInnerHTML("WebSocket连接发生错误");
    };

    //连接成功建立的回调方法
    websocket.onopen = function () {
        // var o = {
        //     message: "请问您有什么需要帮助的吗?"//这里是信息
        // };
        // setMessageInnerHTML(JSON.stringify(o));
        alert("通讯已经连接，请履行你的职责！");
    };

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        // setMessageInnerHTML("WebSocket连接关闭");
        alert("客服人员辛苦了！")
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        // console.log("和后台交互获取的信息"+innerHTML);
        var obj = JSON.parse(innerHTML); //由JSON字符串转换为JSON对象
        answers(obj);
    }

    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }

    function openWebSocket() {
        websocket.open();
    }


    /**
     * 指定用户的函数
     */
    $('.chat_box_left_bottom li').on('click', function () {
        $(".chat_box_right_header").html("");
        $(this).addClass('bg').siblings().removeClass('bg');

        var accountName = $(this).children('.li_right').children('.account').text();
        $(".chat_box_right_header").append("正在和" + "<span></span>" + "对话")
        $('.chat_box_right_header span').text(accountName);
        controllConnection();
    });

    /**
     * 右边对话框的显示和隐藏
     * */
    function controllConnection() {
        var content_id = $(".bg").attr("id");
        //content控制内容的发送
        $("." + content_id).addClass("content").siblings().removeClass('content');
        //content_display控制内容的显示和隐藏
        $("." + content_id).removeClass("content_display").siblings().addClass("content_display");
        $("#textarea").val(''); //清空textarea
    }

    /**
     * 发送消息的函数
     */
    $('.sendBtn').on('click', function () {
        var bg = $(".chat_box_left_bottom").children(".bg");
        if (bg.length == 0) {
            alert("请点击选择交流的账户!");
        } else {
            var sendMessage = $('#textarea').val();
            var sendImage = $(".header_left").children("img").attr("src");
            if (sendMessage == '') {
                alert("请输入要发送的信息");
            } else {
                var str = '';
                str += '<div class="sent_image_header"><img src=' + sendImage + '/></div>' +
                    '<div class="send_content">' + sendMessage + '</div>' +
                    '<div style="clear:both;">' + '</div>';
                $('.content').append(str);

                var acceptId = $(".bg").attr("id");//接收者的Id
                var sendId = $(".header_right").attr("id");//发送者的Id
                var o = {
                    acceptId: acceptId,//这里是要接收的客服id
                    sendId: sendId,//这是发送者的Id
                    message: sendMessage//这里是信息
                };
                var msg = JSON.stringify(o);//要返回的json字符串
                websocket.send(msg);
                $(".bg").children(".li_right").children(".account_accept_message").text(sendMessage.substring(0, 8) + '......');

                $("#textarea").val(''); //清空textarea
                // setTimeout(answers, 1000);

                $('.content').scrollTop($('.content')[0].scrollHeight); //滑动轮直接到底部
            }
        }
    });

    /**
     * 回复消息的函数
     */
    function answers(str) {
        var message = str.message;
        var acceptId = str.acceptId;
        var sendId = str.sendId;
        $("#" + sendId).addClass("bg").siblings().removeClass("bg");
        controllConnection();
        var answerImage = $(".bg").children(".li_left").children("img").attr("src");
        // var str = '生活里，有很多转瞬即逝，像在车站的告别，刚刚还相互拥抱，转眼已各自天涯。很多时候，你不懂，我也不懂，就这样，说着说着就变了，听着听着就倦了，看着看着就厌了，跟着跟着就慢了，走着走着就散了，爱着爱着就淡了，想着想着就算了。';
        var answer = '';
        answer += '<div class="answer_image_header"><img src=' + answerImage + '/></div>' +
            '<div class="answer_content">' + message + '</div>' +
            '<div style="clear:both;">' + '</div>';


        $('.content').append(answer);
        $('.content').scrollTop($('.content')[0].scrollHeight);
    }
</script>
</body>

</html>
